<?php
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

?>

<?php /* @var $block \Magento\Bundle\Block\Adminhtml\Catalog\Product\Composite\Fieldset\Bundle */ ?>
<?php $options = $block->decorateArray($block->getOptions()); ?>
<?php if (count($options)): ?>
<fieldset id="catalog_product_composite_configure_fields_bundle"
          class="fieldset admin__fieldset composite-bundle<?php echo $block->getIsLastFieldset() ? ' last-fieldset' : '' ?>">
    <legend class="legend admin__legend"><span><?php /* @escapeNotVerified */ echo __('Bundle Items') ?></span></legend><br />
    <?php foreach ($options as $option) : ?>
        <?php if ($option->getSelections()) : ?>
            <?php echo $block->getOptionHtml($option); ?>
        <?php endif; ?>
    <?php endforeach; ?>
</fieldset>

<script>
require([
    "Magento_Catalog/catalog/product/composite/configure"
], function(){
    BundleControl = Class.create();

    BundleControl.prototype = {
        initialize: function (config) {
            this.config = config;
        },

        changeSelection: function (selection) {
            if (selection.multiple) {
                return;
            }
            var parts = selection.id.split('-'), optionId = parts[2],
                showQtyInput = selection.value && selection.value != 'none',
                options = this.config.options[optionId],
                selectionOptions = options && options.selections && options.selections[selection.value] || {};

            selectionOptions.can_change_qty = Number(selectionOptions.can_change_qty) && showQtyInput;
            this.updateQtyInput(optionId, selectionOptions);
        },

        updateQtyInput: function(optionId, selectionOptions) {
            var elem = $('bundle-option-' + optionId + '-qty-input'),
                default_qty = Number(selectionOptions.default_qty);
            if (!elem) {
                return;
            }
            if (selectionOptions.can_change_qty) {
                elem.removeClassName('qty-disabled');
                elem.disabled = false;
                elem.value = default_qty || 1;
            } else {
                elem.addClassName('qty-disabled');
                elem.disabled = true;
                elem.value = default_qty || 0;
            }
        },

        updateForDefaults: function () {
            for (var optionId in this.config.options) {
                var selection = $('bundle-option-' + optionId);
                if (selection) {
                    this.changeSelection(selection);
                }
            }
        }
    };
    ProductConfigure.bundleControl = new BundleControl(<?php /* @escapeNotVerified */ echo $block->getJsonConfig() ?>);
});
</script>

<?php endif; ?>
